package com.newgrand.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.newgrand.domain.dbo.Pcm3CntM;
import com.newgrand.domain.model.*;
import com.newgrand.mapper.Pcm3CntMMapper;
import com.newgrand.service.AttachmentService;
import com.newgrand.service.ProjectSubcontractsService;
import com.newgrand.utils.*;
import com.newgrand.utils.i8util.I8Converter;
import com.newgrand.utils.i8util.I8Request;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @创建人：ZhaoFengjie
 * @修改人：ZhaoFengjie
 * @创建时间：18:25 2022/10/17
 * @修改时间:：18:25 2022/10/17
 */
@Service
public class ProjectSubcontractsImpl extends GetPhIdHelper implements ProjectSubcontractsService {
//    private static final String accessId = "zO0IBGSR2vAzY5O3m41G";
//    private static final String secretKey = "M5aXXPJBPIr2dDhLVjNfmNXKjbQj4A4dD84P23asu";
//    private static final String baseUrl = "https://api.mctech.vip";
//    private static OpenApiClient client = new OpenApiClient(baseUrl, accessId, secretKey);

    private static OpenApiClient client = new OpenApiClient(YamlConstants.getPropertiesKey("mc.baseUrl"), YamlConstants.getPropertiesKey("mc.accessId"), YamlConstants.getPropertiesKey("mc.secretKey"));
    private static final String mainApi = "/sm/project-subcontracts?projectId=%s";//&version=%s&limit=%s&offset=%s
    private static final String detailApi = "/sm/project-subcontract/procedures?projectId=%s&subcontractId=%s";//&version=%s&limit=%s&offset=%s&subcontractId=%s
    private static final String attachApi = "/sm/project-subcontract/attachments?projectId=%s&subcontractId=%s";//&version=%s&limit=%s&offset=%s&subcontractId=%s


    private static Logger logger = LogManager.getLogger("logger");
    private static NGLog ngLog = new NGLog();
    @Resource
    private I8Request i8Request;
    private String mstformData = "{\"form\":{\"key\":\"PhId\",\"newRow\":{\"BillNo\":\"\",\"Title\":\"\",\"BillDt\":\"\",\"CntType\":\"2\",\"PhidPc\":\"\",\"CntOrgSumVatFc\":\"\",\"SignDt\":\"\",\"PhidRecComp\":\"\",\"CntSumVatFc\":0,\"Stat\":\"new\",\"PhidSenComp\":\"\",\"ChineseAmtVatFc\":\"\",\"ChSumAmtVatFc\":\"\",\"PhidSchComp\":\"\",\"PhidOcode\":\"\",\"PhidDept\":\"\",\"PhidPm\":\"0\",\"StartDt\":\"\",\"EndDt\":\"\",\"InvoiceCmp\":\"\",\"InvoiceSen\":\"\",\"Remarks\":\"\",\"PayName\":\"\",\"CntOrgSumVat\":\"\",\"PrintCount\":\"\",\"SenEmp\":\"\",\"ChSumAmtVat\":\"\",\"PhidSenEmp\":\"\",\"PhidCm\":\"\",\"CntSumFc\":0,\"CntSumVat\":0,\"BRPcNo\":\"10177\",\"Jhno\":\"\",\"Jhid\":\"\",\"BillType\":\"4\",\"Creator\":\"\",\"NgInsertDt\":\"\",\"PhidGfiOcode\":\"0\",\"ListFilterVal\":\"\",\"QueryField1Val\":\"\",\"QueryField2Val\":\"\",\"UIMultiConfigID\":\"\",\"Py\":\"\",\"PhId\":\"\",\"ChkFlg\":\"0\",\"PhidChkPsn\":\"\",\"DaFlg\":\"\",\"WfFlg\":\"\",\"NgRecordVer\":\"\",\"PhidSchemeId\":\"169220617001010\",\"ImpInfo\":\"\",\"CntSum\":\"0\",\"PhidCheckupId\":\"\",\"PhidXyId\":\"\",\"PhidSourcemid\":\"\",\"ItemResource\":\"\",\"PhidKg\":\"\",\"CntTemplate\":\"\",\"PhIdEntOrgId1\":\"\",\"PhIdEntOrgId2\":\"\",\"PointId\":\"\",\"PhidThdCmp\":\"\",\"ThdEmp\":\"\",\"PhidPe\":\"\",\"RecordStat\":\"0\",\"RecordDt\":\"\",\"PhidWbs\":\"\",\"PhidYsfl\":\"12\",\"FbCompLeader\":\"\",\"CurrType\":\"1\",\"ExchRate\":1,\"Zfbl\":1,\"PhidSeater\":\"\",\"PhidParentId\":\"\",\"CsenEmp\":\"\",\"StampsControl\":\"\",\"PhidStampsitem\":\"\",\"Iscb\":\"0\",\"PhidCountAge\":\"\",\"IsPayFix\":\"1\",\"LogicControlPercent\":1,\"IsPayOverCntSum\":\"1\",\"PayOverPrecent\":1,\"PhidTask\":\"\",\"AsrFlg\":\"\",\"NeedRecord\":\"\",\"IsFixPriceCon\":\"\",\"IsAmtCon\":\"\",\"ToSeat\":\"\",\"IsCntChild\":\"\",\"StampsFlg\":\"\",\"IsBalOverCntSum\":\"\",\"IsPayOverPrecent\":\"\",\"key\":\"\",\"user_mcid\":\"\"}}}";
    private String cntdgridData = "{\"PhId\":\"\",\"Lineid\":1,\"PPhId\":\"\",\"ItemNo\":\"\",\"ItemName\":\"\",\"PhidBoq\":\"\",\"PhidBoq_EXName\":\"\",\"PhidBoqD\":\"\",\"PhidActid\":\"\",\"PhidActid_EXName\":\"\",\"Spec\":\"\",\"Unit\":\"\",\"Unit_EXName\":\"m2\",\"PhidItemId\":\"\",\"PhidItemId_EXName\":\"\",\"Qty\":0,\"Prc\":0,\"PrcVat\":0,\"PrcFc\":0,\"PrcVatFc\":0,\"Amt\":0,\"AmtVat\":0,\"AmtFc\":0,\"AmtVatFc\":0,\"TaxRate\":0.03,\"TaxAmt\":0,\"TimeType\":\"\",\"PhidWbs\":\"\",\"PhidWbs_EXName\":\"\",\"PhidCbs\":\"\",\"PhidCbs_EXName\":\"\",\"PhidProjType\":\"\",\"PhidProjType_EXName\":\"\",\"Character\":\"\",\"Demand\":\"\",\"PhidZbCnt\":\"\",\"PhidZbCnt_EXName\":\"\",\"FzQty\":0,\"QtyOri\":0,\"PrcOri\":0,\"PrcOriVat\":0,\"PrcOriFc\":0,\"PrcOriVatFc\":0,\"OriAmtFc\":0,\"OriAmtVatFc\":0,\"OriAmt\":0,\"OriAmtVat\":0,\"PhidSourceMId\":\"\",\"PhidSourceId\":\"\",\"ItemResource\":\"freeadd\",\"Remarks\":\"\",\"NgRecordVer\":0,\"Creator\":\"\",\"Editor\":\"\",\"CurOrgId\":\"\",\"LevelId\":\"0\",\"PhidFbfw\":\"\",\"PhidFbfw_EXName\":\"\",\"PhidPc\":\"\",\"OperFlg\":\"cnt\",\"PhidCntChg\":\"\",\"ImpInfo\":\"\",\"RestQty\":0,\"RestAmtVat\":0,\"RestAmtVatFc\":0,\"RestAmt\":0,\"RestAmtFc\":0,\"ControlQty\":0,\"ControlAmtVat\":0,\"ControlAmtVatFc\":0,\"ControlAmt\":0,\"ControlAmtFc\":0,\"AuxItems1\":\"\",\"AuxItems3\":\"\",\"AuxItems2\":\"\",\"PhidItemdata\":\"\",\"PhidResBs\":\"\",\"ResPropertys\":\"\",\"CurrType\":\"1\",\"ExchRate\":1,\"Days\":0,\"PhidPc_EXName\":\"醴娄高速总包部七施工分部(10177)\",\"PhidAssetType\":\"\",\"PhidYsfl\":\"\",\"PhidAssetType_EXName\":\"\",\"MustInputCol\":\"\",\"jcqd\":\"\",\"PhidAsset\":\"\",\"IsFarmProduce\":0,\"VendorPrc\":\"\",\"MonthPrcFc\":0,\"MonthPrcVatFc\":0,\"MonthPrc\":0,\"MonthPrcVat\":0,\"OriMonthPrcFc\":0,\"OriMonthPrcVatFc\":0,\"OriMonthPrc\":0,\"OriMonthPrcVat\":0,\"CompStartDt\":0,\"OriCompStartDt\":0,\"Months\":0,\"OriMonths\":0,\"OriMonthsAmt\":0,\"OriMonthsAmtVat\":0,\"OriMonthsAmtFc\":0,\"OriMonthsAmtVatFc\":0,\"MonthsAmt\":0,\"MonthsAmtVat\":0,\"MonthsAmtFc\":0,\"MonthsAmtVatFc\":0,\"MonthsTaxAmt\":0,\"MonthsTaxAmtFc\":0,\"OriMonthsTaxAmtFc\":0,\"OriMonthsTaxAmt\":0,\"ChangePaydDiffAmtVatFc\":0,\"ChangePaydDiffAmtVat\":0,\"ChangePaydDiffAmt\":0,\"ChangePaydDiffAmtFc\":0,\"PhidNonmsunit\":\"\",\"ResMasterData\":\"\",\"ItemDataNo\":\"\",\"BoqCode\":\"\",\"NonMsunit\":\"\",\"Area\":0,\"UmConvAm\":0,\"Weight\":\"\",\"Vol\":\"\",\"CBSAmt\":0,\"CBSAmtVat\":0,\"CBSBalance\":0,\"CBSQty\":0,\"CBSRestQty\":0,\"CBSCntSumAmt\":0,\"CBSBalanceVat\":0,\"CBSCntTypeBalance\":0,\"IMPSourceTbl\":\"\",\"ListModelNo\":\"\",\"BoqLevelName\":\"\",\"ResOtherName\":\"\",\"ResDescript\":\"\",\"CurrType_Name\":\"人民币\",\"ResourceName\":\"\",\"PhidFeeType\":\"\",\"PhidFeeType_EXName\":\"\",\"MBillType\":\"\",\"Cglx\":\"\",\"AssetProp\":\"\",\"AssetCode\":\"\",\"AssetName\":\"\",\"XYCntAmt\":0,\"TotalSumUnVat\":0,\"SumTaxrate\":0,\"RefQty\":0,\"RefAmtVatFc\":0,\"PlanPrc\":0,\"key\":null,\"user_mcid\":\"\",\"user_wzbm\":\"\",\"user_wzbm\":\"\",\"user_ljgz\":\"\",\"user_fyzc\":\"\"}";

    @Resource
    private Pcm3CntMMapper pcm3CntMMapper;
    @Resource
    private AttachmentService attachmentService;

    /**
     * 对应i8分包合同
     *
     * @param data
     * @param orgId
     * @return
     */
    @Override
    public I8ReturnModel<String> save(ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem data, String orgId) {

        String billNo = data.getSubcontractNo();
        try {
            List<Pcm3CntM> itemList = pcm3CntMMapper.selectList(Wrappers.lambdaQuery(Pcm3CntM.class)
                    .eq(Pcm3CntM::getBill_no, data.getSubcontractNo())
                    .or()
                    .eq(Pcm3CntM::getUser_mcid, data.getId().toString()));
            if (!itemList.isEmpty()) {
                for (Pcm3CntM item : itemList) {
                    String user_mcid = item.getUser_mcid();
                    if (StringUtils.isEmpty(user_mcid)) {
                        item.setUser_mcid(data.getId().toString());
                        pcm3CntMMapper.updateById(item);
                    }
                }
                return I8ReturnModel.success();
            }
            String partB = data.getPartB().trim();
            String PhidPc = GetPhIdByCode("project_table", "user_mcxmid", orgId);//pcNo
            String PhidPm = GetPhIdByCode("hr_epm_main", "cname", data.getManager());//pcNo
            String PhidSenComp = GetPhIdByCode("fg3_enterprise", "compname", partB);

            HashMap<String, Object> map = new HashMap<>();
            map.put("PhidPc", PhidPc);
            map.put("BillNo", data.getSubcontractNo());
            map.put("Title", data.getName());
            map.put("BillDt", data.getCreatedAt());
            map.put("SignDt", data.getSignedDate());
            map.put("CntSumVatFc", data.getSubcontractAmount());
            map.put("PhidPm", PhidPm);
            map.put("PhidSenComp", PhidSenComp);
            map.put("PhidRecComp", "758220810000001");//暂定默认湖南交建
            map.put("InvoiceCmp", PhidSenComp);
            map.put("InvoiceSen", "758220810000001");
            map.put("PhidStampsitem", "0");
            map.put("user_mcid", data.getId());
            map.put("PhidSchemeId", "758220812001009");
            map.put("PhidOcode", "758220810001001");
            map.put("CntType", "758220811000002");

            Integer Lineid = 1;
            ArrayList<HashMap<String, Object>> detail = new ArrayList<>();
            List<SubcontractProcedures.SubcontractProceduresDataList.SubcontractProceduresData> detailData = data.getItemList();
            List<NameValuePair> formdata = new ArrayList<>();
            String mstformDataStr = I8Converter.SetField(mstformData, map);
            String cntdgridDataStr;
            if (detailData.isEmpty()) {
                cntdgridDataStr = "{\"table\":{\"key\":\"PhId\"}}";
            } else {
                for (SubcontractProcedures.SubcontractProceduresDataList.SubcontractProceduresData item : detailData) {
                    String Unit = GetPhIdByCode("msunit", "msname", item.getUnit());
                    if (StringUtils.isEmpty(Unit)) {
                        Unit = GetPhIdByCode("msunit", "msname", "kg");//pcNo "169220811000001"; //默认kg
                    }
                    HashMap<String, Object> itemData = new HashMap<>();
                    itemData.put("Lineid", Lineid);
                    itemData.put("ItemNo", item.getId());
                    itemData.put("ItemName", item.getProcedureName());
                    itemData.put("Qty", item.getOriginalQuantity());
                    itemData.put("PrcFc", item.getNonTaxPrice());
                    itemData.put("PrcVatFc", item.getTaxPrice());
                    itemData.put("AmtVatFc", item.getOriginalAmount());
                    itemData.put("AmtFc", item.getOriginalNonTaxAmount());
                    itemData.put("TaxRate", item.getTaxRate() * 0.01);
                    itemData.put("TaxAmt", item.getTax());
                    itemData.put("Unit", Unit);
                    itemData.put("user_mcid", item.getId());
                    itemData.put("user_wzbm", item.getFullCode());
                    itemData.put("user_gznr", item.getJobContent());
                    itemData.put("user_ljgz", item.getMeasurementRule());
                    itemData.put("user_fyzc", item.getCostComposition());
                    detail.add(itemData);
                    Lineid++;
                }
                cntdgridDataStr = I8Converter.SetTableRow(cntdgridData, detail);
            }
            formdata.add(new BasicNameValuePair("mstformData", mstformDataStr));
            formdata.add(new BasicNameValuePair("cntdgridData", cntdgridDataStr));
            formdata.add(new BasicNameValuePair("cntLeveData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntitemparamgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntdescparamgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntptypeparamgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntcollectgridData", "{\"table\":{\"key\":\"PhId\"}}"));
            formdata.add(new BasicNameValuePair("cntmodel", "4"));
            formdata.add(new BasicNameValuePair("bustype", "CON4"));
            formdata.add(new BasicNameValuePair("saveGuid", UUID.randomUUID().toString()));
            formdata.add(new BasicNameValuePair("imptaskid", ""));
            formdata.add(new BasicNameValuePair("isContinue", "false"));
            formdata.add(new BasicNameValuePair("attachOutGuid", "0"));
            formdata.add(new BasicNameValuePair("attchmentGuid", "0"));
            formdata.add(new BasicNameValuePair("ng3_logid", "0"));
            I8ReturnModel<String> res = i8Request.PostFormSyncByOcode("/PMS/PCM/CntM/save", formdata, "101");
            if (res.getIsOk()) {
                String phid = res.getPhId();
                List<AttachMent> attachMentList = data.getAttachMentsList();
                for (AttachMent item : attachMentList) {
                    String name = item.getName();
                    String url = item.getResourceUrl();
                    ngLog.info("ProjectSubcontractsImpl", "附件下载地址：" + url, billNo, "pcm3_cnt_m");
                    String dataBytes = attachmentService.downloadFile(url);
                    ngLog.info("ProjectSubcontractsImpl", "附件二进制数据：" + dataBytes, billNo, "pcm3_cnt_m");
                    attachmentService.postFile(phid, "pcm3_cnt_m", name, dataBytes, "asr_info");
                }
                return I8ReturnModel.success();
            }
            throw new RuntimeException(res.getMessage());
        } catch (Exception ex) {
            ngLog.error("ProjectSubcontractsImpl", "分包合同保存异常", ex.getMessage(), billNo, "pcm3_cnt_m");
            return I8ReturnModel.error(ex.getMessage());
        }
    }

    @Override
    public void saveBatch(List<ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem> data, String orgId) {
        for (ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem item : data) {
            save(item, orgId);
        }
    }


    @Override
    public I8ReturnModel<List<ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem>> getDataByOrgId(String projectId) {
        return I8ReturnModel.success("获取数据成功", getDataListByOrgId(projectId));
    }

    public List<ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem> getDataListByOrgId(String projectId) {
        List<ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem> main = getData(mainApi, projectId);
        for (ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem item : main) {
            Long id = item.getId();
            List<SubcontractProcedures.SubcontractProceduresDataList.SubcontractProceduresData> detail = getDData(detailApi, projectId, id);
            if (!detail.isEmpty()) {
                item.setItemList(detail);
            } else {
                item.setItemList(new ArrayList<>());
            }
            List<AttachMent> attachMentList = getAttachementData(projectId, id);
            if (!attachMentList.isEmpty()) {
                item.setAttachMentsList(attachMentList);
            }
        }
        return main;
    }

    @Override
    public I8ReturnModel<String> saveDataByOrgId(String projectId) {
        try {
            List<ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem> data = getDataListByOrgId(projectId);
            if (!data.isEmpty()) {
                saveBatch(data, projectId);
            } else {
                return I8ReturnModel.success(projectId + "-项目，未获取的需要同步的数据");
            }
        } catch (Exception ex) {
            return I8ReturnModel.error(ex.getMessage());
        }
        return I8ReturnModel.success();
    }

    private List<AttachMent> getAttachementData(String projectId, Long subcontractId) {
        List<AttachMent> dataList = new ArrayList<>();
        while (true) {
            try {
                String apiUrl = String.format(attachApi, projectId, subcontractId);
                RequestResult dataBody = client.get(apiUrl);
                String content = dataBody.getContent();
                if (StringUtils.isEmpty(content)) {
                    break;
                }
                AttachMentData res = JSONObject.parseObject(content, AttachMentData.class);
                dataList = res.getData().getAttachments();
                break;
            } catch (Exception ex) {
                logger.info(String.format("获取表头信息:  %s", ex.getMessage()), ex);
                break;
            }
        }
        return dataList;
    }

    public List<ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem> getData(String url, String projectId) {
        List<ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem> dataList = new ArrayList<>();
        while (true) {
            try {
                String apiUrl = String.format(url, projectId);
                RequestResult dataBody = client.get(apiUrl);
                String content = dataBody.getContent();
                if (StringUtils.isEmpty(content)) {
                    break;
                }
                ProjectSubcontracts res = JSONObject.parseObject(content, ProjectSubcontracts.class);
                List<ProjectSubcontracts.ProjectSubcontractsData.ProjectSubcontractsItem> dataArray = res.getData().getProjectSubcontracts();
                dataList.addAll(dataArray);
                break;
            } catch (Exception ex) {
                logger.info(String.format("获取表头信息:  %s", ex.getMessage()), ex);
                break;
            }
        }
        return dataList.stream().distinct().collect(Collectors.toList());
    }

    public List<SubcontractProcedures.SubcontractProceduresDataList.SubcontractProceduresData> getDData(String url, String projectId, Long subcontractId) {
        Integer offset = 0;//从第N条开始
        Integer limit = 100;//
        Long version = 0L;//本次请求所要获取的增量数据的version起始值，客户端需要存储接口返回的数据集合中最后一条数据version值
        List<SubcontractProcedures.SubcontractProceduresDataList.SubcontractProceduresData> dataList = new ArrayList<>();
        while (true) {
            try {
                String apiUrl = String.format(url, projectId, subcontractId);
                RequestResult dataBody = client.get(apiUrl);
                String content = dataBody.getContent();
                if (StringUtils.isEmpty(content)) {
                    break;
                }
                SubcontractProcedures res = JSONObject.parseObject(content, SubcontractProcedures.class);
                List<SubcontractProcedures.SubcontractProceduresDataList.SubcontractProceduresData> dataArray = res.getData().getSubcontractProcedures();
                dataList.addAll(dataArray);
                break;
            } catch (Exception ex) {
                logger.info(String.format("获取表体信息:  %s", ex.getMessage()), ex);
                break;
            }
        }
        return dataList.stream().distinct().collect(Collectors.toList());
    }


}
